/*****************************************************************************************************************/
// This script adds functionality to adam4adam.com
//
// v 1.0  Displays race and role underneath each profile on the main listing page
//        Flashes the window title if there is new mail
//
// THIS IS A BETA VERSION THAT HAS NOT BEEN THOROUGHLY TESTED.  Use at your own risk.
//---------------------------------------------------------------------------------------------------
//    Copyright (C) 2011  kyfunguy69.  http://kyfunguy69.com
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    For a copy of the latest GNU General Public License, see <http://www.gnu.org/licenses/gpl.html>.
//
//    If you distribute a modified version of this script, you must include the entire
//    section between the dashes starting with "Copyright" and ending here.
//---------------------------------------------------------------------------------------------------
// This script is not sponsored by, endorsed by, or affiliated in any way with ada4adam.com 
//---------------------------------------------------------------------------------------------------
/*****************************************************************************************************************/
var a4a = {
	/* "global" variables */
	version: "1.0",
	prefs: {
		autorun: null,
		race: null,
		role: null,
		flash: null
	},
	title: null,
	flashit: "",
	flashing: false,
	flashopt: false,
	
	/*****************************************************************************************************************
	 *  initialize
	 *  
	 *  Loads jQuery and runs the program once the DOM content has been loaded
	 *****************************************************************************************************************/	    
    initialize: function(){
		var app;
        var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
        loader.loadSubScript("chrome://a4a/content/jquery-1.5.2.min.js");
        $ = jQuery.noConflict();
        if ((app = document.getElementById("appcontent"))) {
            app.addEventListener("DOMContentLoaded", a4a.run, true);
        }
    },
	
	/*****************************************************************************************************************
	 *  run
	 *  
	 *  checks to see if it's the proper page and, if so, runs the program
	 *****************************************************************************************************************/    
    run: function(event){
		try {
			var hostname = event.originalTarget.location.hostname;
			var href = event.originalTarget.location.href;
		}
		catch (err) {
			a4a.debug("a4a error try/catch on a4a.run");
			return;
		}
        if (href && href.match(/http:\/\/(www\.)?adam4adam\.com\//im)) {
			a4a.getPreferences();
			if (a4a.prefs.flash) {
				a4a.title = window.content.document.title;
				window.setInterval(a4a.flash, 5000);
			}
			if (a4a.prefs.autorun && href.match(/http:\/\/(www\.)?adam4adam\.com\/\?section=100\&/im)) {
				 a4a.loadProfiles();
			}
		}
			
		return;
    },
	
	/*****************************************************************************************************************
	 *  getPreferences
	 *  
	 *  loads program preferences from Firefox parameter storage
	 *****************************************************************************************************************/  	
	getPreferences: function() {
			var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.a4a.");
			a4a.prefs.autorun = prefs.getBoolPref("autorun");
			a4a.prefs.race = prefs.getBoolPref("race");
			a4a.prefs.role = prefs.getBoolPref("role");
			a4a.prefs.flash = prefs.getBoolPref("flash");
	},
		
	
	/*****************************************************************************************************************
	 *  loadProfiles
	 *  
	 *  loops through each guy on the screen, captures his screen name and loads his profile page in the background
	 *	passes his profile page to display which extracts and displays the attributes on the screen
	 *****************************************************************************************************************/	    
	loadProfiles: function() {
		if (!a4a.prefs.role && !a4a.prefs.race) { 
			return;
		}
		$("table.boxleftal", window.content.document).each(function() {
			var context = this;		// save the context for display function
			var guy = /\?p=(.*)/im.exec($("tr td a", this).attr("href"));
			if (guy && guy[1]) {		
				$.get("http://www.adam4adam.com/?p=" + guy[1], function(data) {
					a4a.display(data, guy[1], context);
					}, "html"
				);
			}
		});
	},
	
	/*****************************************************************************************************************
	 *  display
	 *  
	 *  parses the attributes from the profile page and displays them on the screen
	 *****************************************************************************************************************/			
	display: function(data, name, context) {
		// delete trace
		var userid = /.*user_id\" value=\"(\d*)/im.exec(data);
		if (userid && userid[1]) {				
			$.post("http://www.adam4adam.com/?section=51&action=delete_trace&profile_id=" + name + "&user_id=" + userid[1]); 
		}
		// get attributes
		var role = "";
		var race = "";
		if (a4a.prefs.role) {
			role = a4a.decode(data, /Sexual Role --> <strong>\s*  (.*).*/im);
		}
		if (a4a.prefs.race) {
			race = a4a.decode(data, /Ethnicity  --><strong>\s*  (.*).*/im);		
		}
		// display on screen
		$("tr td", context).append('<br/><div align="center">' + race + ' ' + role + '</div>');		
	},
	
	
	/*****************************************************************************************************************
	 *  decode(data, regex)
	 *  
	 *  takes an html page and regular expression, parses out the attribute and removes the leading html formatting
	 *	returns the attribute description
	 *****************************************************************************************************************/	
	decode: function(data, regex) {
		var result = "";
		var string = regex.exec(data);
		if (string && string[1]) {
			result =  string[1].replace(/<\/strong>,/im, '');
			result = exceptions(result);
		}
		return result;

		// Exceptions or other transformations		
		function exceptions(text) {
			switch (text) {
				case "Other Ethnicity" :
					text = "Other";
					break;
				case "American Indian" :
					text = "Am Indian";
					break;
			}
			return text;
		}	
	},
	
	/*****************************************************************************************************************
	 *  flash()
	 *  
	 *  Parses the page to get the new email flag.
	 *  If there's new email and it's not flashing, it flashes it
	 *  If there's no new email and it's flashing, it stops it
	 *****************************************************************************************************************/		
	flash: function() {
		var check = /flag_new_email=(\d)/im.exec($("embed", window.content.document).attr("FlashVars"));
		if (check && parseInt(check[1]) == 1) {
			if (!a4a.flashing) {
				a4a.flashit = new a4a.flasher();
				a4a.flashing = true;
			}
		}
		else {
			if (a4a.flashing) {
				a4a.flashit.stop();
				a4a.flashing = false;
			}
		}
	},
	
	/*****************************************************************************************************************
	 *  flasher()
	 *  
	 *  Alternates the title back and forth between the original title and a "new mail" message
	 *****************************************************************************************************************/		
	flasher: function() {
		this.timer = window.setInterval(
			function() {
				if (a4a.flashopt) {
					window.content.document.title = a4a.title;
				}
				else {
					window.content.document.title = "*** New Mail! ***";
				}
				a4a.flashopt = !a4a.flashopt;
			}, 1000);
				
		this.stop = function() { window.clearInterval(this.timer); };
	},
	
	/*****************************************************************************************************************
	 *  debug()
	 *  
	 *  Prints debug messages to the console
	 *****************************************************************************************************************/			
	
	debug: function(msg) {
		Components.classes["@mozilla.org/fuel/application;1"].getService(Components.interfaces.fuelIApplication).mmApplication.console.log(msg);
	}
};

/* runs the extension */
window.addEventListener('load', a4a.initialize, false);
